Introduction
When I wrote a phone index program using VB6, I wanted to add twenty-six Buttons to my form for alphabetical English characters A..Z (one Button holds one character) to search for records in the database file of my phone index. I found it easy because the VB6 allows you to create an array of buttons or an array of any control. When I wanted to re-write the same program using C# or VB.Net I found the addition of twenty-six Buttons to the form not practical because Visual Studio .Net does not have the same capability as VB6 to create an array of controls. In this article you will find it very easy to create an array of buttons using C#; you can use this idea to create a tool for searching in a database file.
This article has two parts.
First part
Explain how to create an array of Buttons.
You can see this trial when you run ButtonArray project.
Remark - When extract the file (ButtonArray.zip) you will find two projects: ButtonArray project, and MyPhone project.
About the Code
//The following procedure to create array of buttons:
private void AddButtons()
{
int xPos = 0;
int yPos = 0;
System.Windows.Forms.Button[] btnArray = new System.Windows.Forms.Button[26];
for (int i = 0; i < 26; i++)
{
btnArray[i] = new System.Windows.Forms.Button();
}
int n = 0;
while(n < 26)
{
btnArray[n].Tag = n + 1;
btnArray[n].Width = 24;
btnArray[n].Height = 20;
if(n == 13)
{
xPos = 0;
yPos = 20;
}
btnArray[n].Left = xPos;
btnArray[n].Top = yPos;
pnlButtons.Controls.Add(btnArray[n]);
xPos = xPos + btnArray[n].Width;
btnArray[n].Text = ((char)(n + 65)).ToString();
btnArray[n].Click += new System.EventHandler(ClickButton);
n++;
}
btnAddButton.Enabled = false;
label1.Visible = true;
}
public void ClickButton(Object sender, System.EventArgs e)
{
Button btn = (Button) sender;
MessageBox.Show("You clicked character [" + btn.Text + "]");
}
Second part
Explain how to use the twenty-six Buttons to write a program for a phone index to see how we can use the alphabetical English characters (A..Z) to search a customer name which begin with a character; you can also read about some methods of ADO.NET.
You can see this trial when you run MyPhone project after extracting the file (ButtonArray.zip).
About the Code
// Result of the event click Button, get the text of button and find record
Remark
After extracting the file (ButtonArray.zip) you can open the MyPhone project to read the remaining code about use of ADO methods and see the result when running the program.
I hope this article is useful; if you have any idea, please tell me.